"""
WebSocket事件处理
"""

from flask_socketio import emit, join_room, leave_room
from flask_jwt_extended import jwt_required, get_jwt_identity
from app import socketio
from app.models import User, Notification
from app import db

@socketio.on('connect')
@jwt_required()
def handle_connect():
    """客户端连接"""
    user_id = get_jwt_identity()
    user = User.query.get(user_id)
    
    if user:
        # 加入用户专属房间
        join_room(f'user_{user_id}')
        emit('connected', {'message': '连接成功', 'user_id': user_id})
    else:
        emit('error', {'message': '用户不存在'})
        return False

@socketio.on('disconnect')
def handle_disconnect():
    """客户端断开连接"""
    print('客户端断开连接')

@socketio.on('join_room')
@jwt_required()
def handle_join_room(data):
    """加入房间"""
    room = data.get('room')
    if room:
        join_room(room)
        emit('joined_room', {'room': room})

@socketio.on('leave_room')
@jwt_required()
def handle_leave_room(data):
    """离开房间"""
    room = data.get('room')
    if room:
        leave_room(room)
        emit('left_room', {'room': room})

@socketio.on('subscribe_notifications')
@jwt_required()
def handle_subscribe_notifications():
    """订阅通知"""
    user_id = get_jwt_identity()
    join_room(f'notifications_{user_id}')
    emit('subscribed', {'type': 'notifications'})

@socketio.on('subscribe_scheduling')
@jwt_required()
def handle_subscribe_scheduling():
    """订阅调度更新"""
    user_id = get_jwt_identity()
    user = User.query.get(user_id)
    
    if user and user.role in ['admin', 'doctor']:
        join_room('scheduling_updates')
        emit('subscribed', {'type': 'scheduling'})
    else:
        emit('error', {'message': '无权限订阅调度更新'})

def send_notification(user_id, title, content, notification_type='system'):
    """发送通知"""
    # 保存通知到数据库
    notification = Notification(
        user_id=user_id,
        title=title,
        content=content,
        notification_type=notification_type
    )
    db.session.add(notification)
    db.session.commit()
    
    # 通过WebSocket发送实时通知
    socketio.emit('notification', {
        'id': notification.id,
        'title': title,
        'content': content,
        'type': notification_type,
        'timestamp': notification.created_at.isoformat()
    }, room=f'notifications_{user_id}')

def send_scheduling_update(update_type, data):
    """发送调度更新"""
    socketio.emit('scheduling_update', {
        'type': update_type,
        'data': data,
        'timestamp': datetime.now().isoformat()
    }, room='scheduling_updates')

def send_appointment_reminder(user_id, appointment_data):
    """发送预约提醒"""
    title = '预约提醒'
    content = f'您的预约将在{appointment_data["scheduled_time"]}开始，请提前15分钟到达。'
    
    send_notification(user_id, title, content, 'appointment')

def send_schedule_change(user_id, old_time, new_time):
    """发送排程变更通知"""
    title = '排程变更通知'
    content = f'您的预约时间已从{old_time}调整为{new_time}，请确认。'
    
    send_notification(user_id, title, content, 'schedule')
